#!/usr/bin/env python
#Name: QuizPackBETA (Functions)
#Version: 0.5
#Created by Alex/The OniOwl Project
#(C) 2007 Alex/The OniOwl Project
#
#Released under the GNU General Public License
#which can be found at: (http://www.gnu.org/copyleft/gpl.html) or the included LICENSE file
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
import sys
import os
import random
import string
import ConfigParser
if __name__ == "__main__":
    print "Run either quizpackgui.py or quizpacktext.py"
    sys.exit()
questions=[]
answers = []
qcount = 0
questionsans = []
keywordignore = ['A', 'and', 'the']
usercorrect = 0
totalans = 0
quiztype = ''
name = 'QuizPackBETA'
version = '0.5-SVN'

def change_to_correct_path():
    #Thanks to the PyGame Cookbook
    exe_base_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
    os.chdir(exe_base_dir)
    sys.path.append(exe_base_dir)
def read_lang(filename):
    global language
    language = ConfigParser.RawConfigParser()
    language.readfp(open(filename)) 
def packfile(fname):
    '''Reads a pack file and opens the specified question and answer files.'''
    global quiztype
    purgeqa()
    pckfile = open(fname)
    
    try:
        for line in pckfile:
            rline=line.replace('\n','')
            if not line.startswith('#'):
                if rline.endswith('.qzq'):
                    writeqa(line.replace('\n',''), 'q')
                if rline.endswith('.qza'):
                    writeqa(line.replace('\n',''), 'a')
                if rline.startswith('type='):
                    if rline.endswith('keyword'):
                        quiztype='keyword'
                    if rline.endswith('exact'):
                        quiztype='exact'
    finally:
        pckfile.close()

def writeqa(fname, qa):
    '''Writes the questions to the "questions" list and answers to the "answers" list.'''
    global questions
    global answers
    global qcount
    try:
        qafile = open(fname)
    except IOError:
        print 'Error opening quizpack.'
        sys.exit()
    try:
        for line in qafile.readlines():
            if not line.startswith('#'):
                if qa == 'q':
                    questions.append(line)
                    qcount = qcount+1
                elif qa == 'a':
                    answers.append(line)
                else:
                    print 'It was not specified if the file was a question or answer file!'
    finally:
        questions=map(string.strip, questions)
        answers=map(string.strip, answers)
        qafile.close()

def checkqa():
    '''Makes sure there are an equal number of questions and answers'''
    for each in questions:
        qtotal=qtotal+1
    for each in answers:
        atotal=atotal+1
    if qtotal!=atotal:
        print 'The question and answer files do not have an equal number of strings.'
        sys.exit()

def purgeqa():
    '''Clears out the question and answer lists.'''
    questions = []
    answers = []
    global quiztype
    quiztype = ''

def questionnumpick():
        global questionnum
        global qcount
        global totalans
        questionnum = random.randint(0, qcount-1)
        if totalans == qcount:
                leave()
        if questionnum in questionsans:
                questionnumpick()

def evalanswer(useranswer):
    '''Based on the type of quizpack it checks the answer.'''
    global quiztype
    global questionnum
    global usercorrect
    try:
        if quiztype=='exact':
            if useranswer==answers[questionnum]:
                correct=0
            else:
                correct=1
#Keyword checking isn't complete, need to check the accuracy of the user's answer.
        if quiztype=='keyword':
            #Get keywords from the answer
            keywordschecked=0
            keywordsimpt=[]
            keywordsall = answers[questionnum].partition(' ')
            check = keywordsall[keywordstried]
            try:
                if check in keywordignore:
                    keywordschecked=keywordschecked+1
                else:
                    keywordsimpt.append[keywordsall[keywordschecked]]
                    keywordschecked=keywordschecked+1
            except IndexError:
                pass
            #Get keywords from useranswer
            
            #Compare user's keywords with actual keywords
            if useranswer == answers[questionnum]:
                correct=0
#        if quiztype=='keyword':
#            keywordsall = answers[questionnum].partition(' ')
#            for str in keywordsall:
#                print 'STRING!'
            
        else:
            print 'Quiztype not specified or invalid type. Assuming exact checking.'
            quiztype='exact'
            if useranswer==answers[questionnum]:
                correct=0
            else:
                correct=1
    except NameError:
        print 'Quiztype not defined. Assuming exact checking.'
        quiztype='exact'
        if useranswer==answers[questionnum]:
            correct=0
        else:
            correct=1
    if correct==0:
        print 'Correct, it is', answers[questionnum]+'\n'
        usercorrect=usercorrect+1
    if correct==1:
        print 'WRONG'
        print 'The correct answer was:', answers[questionnum]+'\n'
def leave():
    '''Tells the user how many right out of total questions answered, then exits.'''
    global totalans
    global usercorrect
    print 'You got', usercorrect, 'out of', totalans, 'questions.'
    sys.exit()
